package com.sesame.producer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import kim.sesame.framework.rocketmq.core.RocketMQTemplate;
import kim.sesame.framework.rocketmq.msg.MsgObject;
import kim.sesame.common.utils.UUIDUtil;
import kim.sesame.common.web.controller.AbstractWebController;
import kim.sesame.common.result.ApiResult;
import lombok.extern.apachecommons.CommonsLog;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.producer.SendResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@CommonsLog
@RestController
@RequestMapping("/producer")
public class ProducerController extends AbstractWebController {

    static final String topic1 = "test-topic-1";

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    /**
     * http://127.0.0.1:8091/producer/send1?msg=1111
     */
    @RequestMapping("/send1")
    public ApiResult send1(String msg) {
        if (StringUtils.isEmpty(msg)) {
            msg = "hello word";
        }
        SendResult result = rocketMQTemplate.syncSend(topic1, "tag1", msg, null);

        return success(result);
    }

    /**
     * http://127.0.0.1:8091/producer/send2?msg=1111&id=ab
     */
    @RequestMapping("/send2")
    public ApiResult send2(String msg, String id) {
        if (StringUtils.isEmpty(msg)) {
            msg = "hello word";
        }
        if (StringUtils.isEmpty(id)) {
            id = UUIDUtil.getShortUUID();
        }
        MsgObject mo = new MsgObject(id, msg);
        String josn = JSON.toJSONString(mo, SerializerFeature.UseSingleQuotes);
        SendResult result = rocketMQTemplate.syncSend(topic1, "tag2", josn, null);

        return success(result);
    }

    /**
     * http://127.0.0.1:8091/producer/test?msg=1111
     */
    @RequestMapping("/test")
    public ApiResult test(String msg) {
        if (StringUtils.isEmpty(msg)) {
            msg = "hello word";
        }
        SendResult result = rocketMQTemplate.syncSend("test-topic", "test-tag", msg, null);

        return success(result);
    }

}
